import React, { useEffect, useRef, useState } from 'react'
import { Button, Cascader, Flex, Form, Input, message, Modal, Select, Typography } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import GoBack from "@/components/TheGoBack";
import TheQuill from "@/components/TheQuill/index.jsx";
import TheUpload from "@/components/TheUpload";
import Specification from '../specification'
import { freightTemplateDetails, freightTemplatePage } from '@/api/goodsManagement/freightTemplate.js';
import {
  getPetTagsList,
  getStoreClassifyTree,
  getStoreGoodsAdd,
  getStoreGoodsDetails,
  getStoreGoodsEdit
} from '@/api/goodsManagement/goodsList.js';
import { ProForm, ProFormCascader, ProFormSelect, ProFormText ,ProFormSwitch } from "@ant-design/pro-components";

const { Paragraph } = Typography;

export default function goodsManagement() {
  const navigate = useNavigate();
  const location = useLocation(); //参数以及路由地址
  const InfoFormRef = useRef() //基本信息表单ref
  const FreightFormRef = useRef() //运费表单ref
  const SKURef = useRef() //商品规格ref
  const [suitablePetOptions, setSuitablePetOptions] = useState([]) // 适用宠物
  const [categoryOptions, setCategoryOptions] = useState([]) // 类目
  const [freightOptions, setFreightOptions] = useState([]) // 运费
  const [currentPage, setCurrentPage] = useState(0) //下一页、上一页
  const [dataSource, setDataSource] = useState([]) // 规格表格数据
  const [columns, setColumns] = useState([]) // 规格表头
  const [productTxt, setProductTxt] = useState() // 商品详情
  const [saveLoading, setSaveLoading] = useState(false) // 保存loading
  const [saveUpLoading, setSavUpLoading] = useState(false) // 保存并上传loading
  const [goodsId, setGoodsId] = useState()//商品id
  const [storeGoodsId, setStoreGoodsId] = useState()//店铺id
  const [skuId, setSkuId] = useState(null) //skuId
  const [mode, setMode] = useState()
  const [tempData, setTempData] = useState([])
  useEffect(() => {
    if (location.state) {
      setMode(location.state.mode)
      if (location.state.mode !== 'add') {
        setGoodsId(location.state.id)
        setStoreGoodsId(location.state.storeId)
        getData(location.state.id, location.state.storeId)
      }
    }
    getFreightOptions()
    getPetTags()
    getStoreClassify()
  }, [])

  //数据详情回显处理
  const getData = async (goodsId, storeGoodsId) => {
    await getStoreGoodsDetails({ goodsId, storeGoodsId }).then(res => {
      if (res.code === 0 && res.data) {
        let goodsInfoVo = res.data.nonSelfGoodsInfoDTO
        let skuInfoVo = res.data.nonSelfGoodsSkuDTOList
        let goodsClassifyId = goodsInfoVo.goodsClassifyId.split(',') //商品类目
        let goodsTag = goodsInfoVo.goodsTag.split(',') //适用宠物
        let productSkuJson = JSON.parse(goodsInfoVo.productSkuJson) //规格设置
        SKURef.current.formRef.setFieldsValue({ productSkuJson: productSkuJson, table: [...skuInfoVo] })
        // console.log(SKURef.current.formRef.getFieldsValue());
        InfoFormRef.current.setFieldsValue({
          ...goodsInfoVo,
          goodsClassifyId,
          goodsTag
        }) // 基本信息
        FreightFormRef.current.setFieldsValue({ freightTemplateId: goodsInfoVo.freightTemplateId }) //运费模板
        setProductTxt(goodsInfoVo.productTxt)
      }
    })
  }
  // 适用宠物
  const getPetTags = async () => {
    await getPetTagsList({ type: 'goods_tag' }).then(res => {
      if (res.code === 0 && res.data) {
        setSuitablePetOptions(res.data)
      }
    })
  }
  // 商品类目
  const getStoreClassify = async () => {
    await getStoreClassifyTree().then(res => {
      if (res.code === 0) {
        let data = []
        if (res.data.length === 0 || res.data === null) {
          Modal.warning({
            title: '提示',
            content: '请先联系哈奇马客服开通此类目权限'
          });
        } else {
          data = res.data.map((v) => {
            return {
              value: v.value,
              label: v.label,
              children: v.children.length > 0 ? v.children : []
            }
          })
          setCategoryOptions(data)
        }
      }
    })
  }
  // 运费模板
  const getFreightOptions = async () => {
    await freightTemplatePage({ pageNo: 1, pageSize: 9999 }).then(res => {
      if (res.code === 0) {
        if (res.data !== null) {
          setFreightOptions(res.data)
        } else {
          Modal.warning({
            title: '提示',
            content: '请先配置运费模板！'
          });
        }
      }
    })
  }
  const nextPage = async (currentPage) => {
    let flag = true;
    // let formRefData = [];

    if (currentPage) {
      await InfoFormRef.current.validateFields().catch(value => { flag = false }) //校验基本信息是否填写
      await FreightFormRef.current.validateFields().catch(value => { flag = false }) //校验运费信息是否填写
      await SKURef.current.formRef.validateFields()
        // .then(data=>{
        //   console.log(data)
        // })
        .catch(value => {
          message.info("请填写完整的商品规格信息")
          flag = false
        })
      if (!flag) {
        return
      }
      await SKURef.current.editRef.validateFields()
        // .then(data=>{
        //   // for(let key in data){
        //   //   editRefData.push(data[key])
        //   // }
        //   // editRefData.map((item,index)=>{
        //   //   formRefTableData[index] = {
        //   //     ...formRefTableData[index],
        //   //     ...item,
        //   //   }
        //   // })
        //   // setTempData(formRefTableData)
        // })
        .catch(value => {
          message.info("请填写完整的规格设置信息")
          flag = false
        })
    }
    if (!flag) {
      return
    }
    setCurrentPage(currentPage)
  }
  // 接口处理
  const getParams = async (params) => {
    if (params.insertType === 1) {
      setSaveLoading(true)
    } else {
      setSavUpLoading(true)
    }
    if (params.productTxt === undefined || params.productTxt === '<p></p>') {
      message.error('请填写商品详情！')
    } else {
      let goodsClassifyId = params.goodsClassifyId.join(',') //商品类目数据处理
      let goodsTag = params.goodsTag.join(',') //适用宠物数据处理
      let productSkuJson = JSON.stringify(params.productSkuJson) //商品规格数据处理
      let value = {
        insertType: params.insertType, //操作类型
        storeGoodsId: storeGoodsId,
        nonSelfGoodsInfoDTO: {
          goodsClassifyId,//商品类目数据
          goodsTag,//适用宠物
          productSkuJson, //规格数据
          freightTemplateId: params.freightTemplateId, //邮费
          goodsName: params.goodsName, //商品名称
          productTxt: params.productTxt, //商品详情
          goodsShowImages: params.goodsShowImages,//商品图片
          isVirtual: params.isVirtual?1:0,//是否为虚拟物品
        },
        // nonSelfGoodsSkuDTOList: [...params.table]
        // nonSelfGoodsSkuDTOList: SKURef.current.getData()
      }
      if (SKURef.current.getData()) {
        value.nonSelfGoodsSkuDTOList = SKURef.current.getData()
      } else {
        value.nonSelfGoodsSkuDTOList = [...params.table]
      }
      if (storeGoodsId && goodsId) {
        await getStoreGoodsEdit({ ...value }).then(res => {
          if (res.code === 0) {
            if (params.insertType === 1) {
              message.success('保存成功')
            } else {
              message.success('上架成功')
            }
            navigate(-1) // 返回上一页
          }
        })
      } else {
        await getStoreGoodsAdd({ ...value }).then(res => {
          if (res.code === 0) {
            if (params.insertType === 1) {
              message.success('保存成功')
            } else {
              message.success('上架成功')
            }
            navigate(-1) // 返回上一页
          }
        })
      }
    }
    if (params.insertType === 1) {
      setSaveLoading(false)
    } else {
      setSavUpLoading(false)
    }
  }
  // 保存
  const saveGoods = () => {
    let value = {
      insertType: 1,
      storeGoodsId,//商品id
      ...InfoFormRef.current.getFieldsFormatValue(), //基本信息数据
      ...SKURef.current.formRef.getFieldsValue(), //规格设置
      ...FreightFormRef.current.getFieldsValue(), //运费模板
      productTxt,//商品详情
    }
    getParams(value)

  }
  // 保存并上架
  const savePutAwayGoods = () => {
    let value = {
      insertType: 2,
      storeGoodsId,//商品id
      ...InfoFormRef.current.getFieldsFormatValue(), //基本信息数据
      ...SKURef.current.formRef.getFieldsValue(), //规格设置
      ...FreightFormRef.current.getFieldsValue(), //运费模板
      productTxt,//商品详情
    }
    getParams(value)
  }

  const formItemLayout = { labelCol: { flex: "130px" }, wrapperCol: { span: 6 } };
  return (
    <div className='wrap-box wrap-box-content'>
      <GoBack title={goodsId && storeGoodsId ? '修改商品' : "新建商品"} />
      <div className={'wrap-box-content'} style={{ display: currentPage === 0 ? 'block' : 'none' }}>
        <Paragraph strong>
          <blockquote>基本信息</blockquote>
        </Paragraph>
        <ProForm
          {...formItemLayout}
          formRef={InfoFormRef}
          layout={'horizontal'}
          submitter={false}
        // onFinish={(values) => {
        //   console.log('Received values of form: ', values);
        // }}
        >
          {/*<Form.Item {...formItemLayout} label="商品名称" name="goodsName" rules={[{ required: true }]}>*/}
          {/*  <Input maxLength={100} placeholder="请输入商品名称" />*/}
          {/*</Form.Item>*/}
          {/*<Form.Item {...formItemLayout} label="适用宠物" name="goodsTag" rules={[{ required: true }]}>*/}
          {/*  <Select mode="multiple" allowClear placeholder="请选择适用宠物" options={suitablePetOptions} fieldNames={{ label: 'value', value: 'dictionariesId' }} />*/}
          {/*</Form.Item>*/}
          {/*<Form.Item {...formItemLayout} label="商品类目" name="goodsClassifyId" rules={[{ required: true }]}>*/}
          {/*  <Cascader options={categoryOptions} placeholder="请选择商品类目" />*/}
          {/*</Form.Item>*/}
          <ProFormText
            label="商品名称"
            name="goodsName"
            rules={[{ required: true }]}
            fieldProps={{
              maxLength: 100,
              placeholder: '请输入商品名称'
            }}
          />
          <ProFormSelect
            label="适用宠物"
            name="goodsTag"
            options={suitablePetOptions}
            rules={[{ required: true }]}
            fieldProps={{
              mode: 'multiple',
              fieldNames: { label: 'name', value: 'dictionariesId' },
              maxLength: 100,
              placeholder: '请选择适用宠物'
            }}
          />
          <ProFormCascader
            label="商品类目"
            name="goodsClassifyId"
            rules={[{ required: true }]}
            placeholder={'请选择商品类目'}
            fieldProps={{
              options: categoryOptions,
            }}
          />
          <TheUpload label="商品图" name="goodsShowImages" required={true} />
          <ProFormSwitch
              disabled={mode == 'edit'}
            label="是否为虚拟商品"
            name="isVirtual"
          />
        </ProForm>
        <Paragraph strong>
          <blockquote>运费</blockquote>
        </Paragraph>
        <Form
          {...formItemLayout}
          ref={FreightFormRef}
        >
          <Form.Item label="运费模板" name="freightTemplateId" rules={[{ required: true }]}>
            <Select placeholder="请选择运费模板" options={freightOptions} fieldNames={{ label: 'freightTemplateName', value: 'freightTemplateId' }} />
          </Form.Item>
        </Form>
        <Paragraph strong>
          <blockquote>价格库存</blockquote>
        </Paragraph>
        <Specification defaultData={[]} mode={mode} ref={SKURef} />
        <Flex justify={'center'} align={'center'} gap={'middle'}>
          <Button onClick={() => history.go(-1)}>取消</Button>
          <Button onClick={() => nextPage(1)}>下一页</Button>
        </Flex>
      </div>
      <div style={{ display: currentPage === 1 ? 'block' : 'none' }}>
        <Paragraph strong>
          <blockquote>商品详情页</blockquote>
        </Paragraph>
        <TheQuill defaultValue={productTxt} setNewsContent={setProductTxt} />
        <Flex justify={'center'} align={'center'} gap={'middle'}>
          <Button onClick={() => history.go(-1)}>取消</Button>
          <Button onClick={() => nextPage(0)}>上一步</Button>
          <Button onClick={saveGoods} loading={saveLoading}>保存</Button>
          <Button onClick={savePutAwayGoods} loading={saveUpLoading}>保存并上架</Button>
        </Flex>
      </div>
    </div>
  )
}
